<template>
  <section class="one-image-upload">
    <div>
      <el-button :loading="uploading" @click="openFile($event)">
        <i class="el-icon-upload"></i> 上传图片
      </el-button>
      <input type="file" ref="file" @change="changeFile($event)" style="display: none;">
    </div>
    <div>
      <small class="gay_color">
        <slot></slot>
      </small>
    </div>
    <el-input v-model="imgUrl" @change="changeInput" v-show="false"></el-input>
  </section>
</template>
<script>
import OssFile from "@/_js/OssFile.js";
import Config from "@/_config/config.js";
export default {
  props: {
    value: String,
    //文件上传大小限制 默认2M
    fileSize: {
      type: Number,
      default: 2097152
    }
  },
  data() {
    return {
      imgUrl: "",
      uploading: false
    };
  },
  created() {
    let th = this;
  },
  methods: {
    changeInput(e) {
      this.$emit("change", this.imgUrl);
    },
    //   reqUrl: string = Config.reqUrl.fileUrl;
    openFile(e) {
      this.$refs["file"].click();
    },
    //上传完成
    UpFileSuccess(path) {
      let th = this;
      th.imgUrl = path;
      th.$emit("success",path);
      th.$emit("input", path);
    },
    //开始上传
    changeFile(e) {
      let th = this;
      if (e.target.files.length == 0) return;
      let file = e.target.files[0];
      let size = th.fileSize;
     
      if (file.type != "image/png" && file.type != "image/jpeg") {
        th.$message.warning("只能上传png/jpg");
        return;
      }
       if (file.size > size) {
        th.$message.warning(`最大支持${Math.round(th.fileSize / 1048576)}m`);
        return;
      }
      th.uploading = true;
      th.$emit("begin")
      th.$api.getTemporaryAKAndToken("web").then(res => {
        if (res.excute) {
          OssFile.uploadImage(file, res)
            .then(res => {
              th.uploading = false;
              //返回数据
              th.UpFileSuccess(res.path);
            })
            .catch(function(err) {
              th.uploading = false;
              th.$message.error("上传出错");
            });
        }
      });
    }
  }
};
</script>
 <style lang="scss">
.one-image-upload {
  display: flex;
  align-items: center;
  > div:nth-child(1) {
    flex-shrink: 0;
    position: relative;
  }
  > div:nth-child(2) {
    flex-grow: 1;
    margin-left: 10px;
  }
}
</style>
 
